package com.mbds.accelerometer;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.mbds.accelerometer.db.SensorDB;
import com.mbds.utils.DataCollectionTimer;
import com.mbds.utils.TruncateTask;

public class SensorDataManager  {
	
	private SensorDB db;
	private Sensor sensor;
	private SensorManager sensorManager;
	
	private DataCollectionTimer timer;
	
	private static SensorDataManager singleton;
	
	private SensorEventListener sensorEventListener = new SensorEventListener() {
		
		@Override
		public void onSensorChanged(SensorEvent event) {
			SensorDB.getInstance().addValues( event.values[0],  event.values[1],  event.values[2]);
			
		}
		
		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {}
	};
	
	
	private SensorDataManager(Context context) {
		SensorDB.init(context);
		db = SensorDB.getInstance();
		sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
		sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
				
		timer = new DataCollectionTimer(new TruncateTask());
		startDataCollection();
		
	}	
	
	public static void init(Context context) {
		if(singleton == null) {
			singleton = new SensorDataManager(context);
		}
	}
	
	public static SensorDataManager getInstance() {
		return singleton;
	}
	
	/**
	 * We add saveTask in the list of listener of accelerometer, open data base and 
	 * the task do their job
	 */
	public void startDataCollection() {
		sensorManager.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
		db.openDB();
		timer.startTasks();
	}
	
	/**
	 * Stop data collection : 
	 * the task do noting, unregister the listener of accelerometer and close data base
	 */
	public void stopDataCollection() {
		sensorManager.unregisterListener(sensorEventListener);
		db.close();
		timer.stopTasks();
	}
	
}
